import { http } from '@/plugins/axios'
import useUtils from '@/utils'
const { encodeSearchParams } = useUtils()
import axios from 'axios'
const storage = useStorage()
const formattedDate = () => {
  let date = new Date();
  const year = date.getFullYear();
  const month = (date.getMonth() + 1).toString().padStart(2, '0');
  const day = date.getDate().toString().padStart(2, '0');
  const hour = date.getHours().toString().padStart(2, '0');
  const minute = date.getMinutes().toString().padStart(2, '0');
  const second = date.getSeconds().toString().padStart(2, '0');
  const formattedDateStr = `${year}-${month}-${day} ${hour}:${minute}:${second}`;
  return formattedDateStr
}

export default () => {
  const index = async (page: number = 1, obj: Object) => {
    let data = encodeSearchParams(obj)
    return await http.request<any>({
      url: `log?page=${page}&${data}`,
      method: "GET",
    })
  }

  const download = async () => {
    return await axios({
      url: `/api/log/export`,
      headers: {
        "Authorization": `Bearer ${storage.get(CacheEnum.TOKEN_NAME)}`
      },
      responseType: 'blob',
      method: "GET"
    }).then((res) => {
      console.log(res)
      const link = document.createElement('a')
      const blob = new Blob([res.data], { type: 'application/vnd.ms-excel' })
      link.style.display = 'none'
      link.href = URL.createObjectURL(blob)
      link.setAttribute('download', `${formattedDate()}.xlsx`)
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
    })
  }
  return {
    index,
    download
  }
}
